//
//  GetLocation.m
//  BrotherMovProject
//
//  Created by zhibao on 2022/1/19.
//

#import "GetLocation.h"
#import <CoreLocation/CoreLocation.h>
#import <CoreFoundation/CoreFoundation.h>
static GetLocation *instance = nil;
@interface GetLocation ()<CLLocationManagerDelegate>{

}
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *geocoder;
@end
@implementation GetLocation
+ (GetLocation *)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[GetLocation alloc] init];
    });
    return instance;
}
-(id)init{
    self = [super init];
    if (self) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        // 检查当前授权状态
        [self checkLocationAuthorizationStatus];
        self.geocoder = [[CLGeocoder alloc] init];
        [self.locationManager startUpdatingLocation];
        
    }
    return self;
}
- (void)checkLocationAuthorizationStatus {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    switch (status) {
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            // 当应用程序在使用时，用户已授权位置服务
            NSLog(@"位置服务权限已开启（使用时）");
            break;
            
        case kCLAuthorizationStatusAuthorizedAlways:
            // 用户已授权位置服务，即使应用程序不在前台
            NSLog(@"位置服务权限已开启（始终）");
            break;
            
        case kCLAuthorizationStatusDenied:
            // 用户已拒绝位置服务
            NSLog(@"位置服务权限已关闭");
            // 你可能需要向用户展示一个提示，解释为什么需要位置权限
            // 你可以在这里请求用户授权
            if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                [self.locationManager requestWhenInUseAuthorization];
            }
            break;
            
        case kCLAuthorizationStatusRestricted:
            // 位置服务被系统限制（例如，家长控制）
            NSLog(@"位置服务被系统限制");
            break;
            
        case kCLAuthorizationStatusNotDetermined:
            // 用户尚未做出选择（通常是在首次请求权限时）
            NSLog(@"位置服务权限未确定");
            // 你可以在这里请求用户授权
            if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                [self.locationManager requestWhenInUseAuthorization];
            }
            break;
            
        default:
            break;
    }
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [manager stopUpdatingLocation];
    CLLocation *location = [locations lastObject];
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        LocationModel *model = [LocationModel new];
        model.isTift = @"";
        model.provinceCode = @"";
        model.addInfo = @"";
        model.lon = 0.00;
        model.numberPlate = @"";
        model.floorContent = @"";
        model.areaCode = @"";
        model.contactsPhone = @"";
        model.areaName = @"";
        model.evident = @"";
        model.moveAddressType = @"0";
        model.provinceName = @"";
        model.cityID = @"464";
        model.cityName = @"北京市";
        model.cityCode = @"110100";
        model.lat = 0.00;
        if (placemarks.count > 0 && error == nil) {
            CLPlacemark *placemark = placemarks[0];
            NSString *province = placemark.administrativeArea;
            NSString *city = placemark.locality;
            NSString *district = placemark.subLocality;
            DLog(@"当前省份: %@，当前城市: %@，当前区/县: %@ addressDictionary:%@", province, city, district,placemark.thoroughfare);
            
            model.provinceCode = placemark.administrativeArea;
            model.addInfo = placemark.addressDictionary[@"FormattedAddressLines"];
            model.lon = placemark.location.coordinate.longitude;
            model.areaCode = placemark.postalCode;
            model.cityCode = placemark.postalCode;
            model.cityName = placemark.locality;
            model.areaName = placemark.subLocality;
            model.POIName = placemark.name;
            model.lat = location.coordinate.latitude;
            DLog(@"addresssDic==%@",model.addInfo);
            if (self.GetLocationBlock) {
                self.GetLocationBlock(model);
            }
            
        } else {
            NSLog(@"逆地理编码出错: %@", error.localizedDescription);
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"获取位置信息出错: %@", error.localizedDescription);
}
- (void)getLoctaion{
    // 带逆地理信息的一次定位（返回坐标和地址信息）
   
    //   定位超时时间，最低2s，此处设置为10s
//    self.locationManager.locationTimeout =10;
//    //   逆地理请求超时时间，最低2s，此处设置为10s
//    self.locationManager.reGeocodeTimeout = 10;
//    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
//    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
//            
//        LocationModel *model = [LocationModel new];
//        model.isTift = @"";
//        model.provinceCode = @"";
//        model.addInfo = @"";
//        model.lon = 0.00;
//        model.numberPlate = @"";
//        model.floorContent = @"";
//        model.areaCode = @"";
//        model.contactsPhone = @"";
//        model.areaName = @"";
//        model.evident = @"";
//        model.moveAddressType = @"0";
//        model.provinceName = @"";
//        model.cityID = @"464";
//        model.cityName = @"北京市";
//        model.cityCode = @"110100";
//        model.lat = 0.00;
//            if (error)
//            {
//                NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//                
//                if (error.code == AMapLocationErrorLocateFailed)
//                {
//                    if (self.GetLocationBlock) {
//                        self.GetLocationBlock(model);
//                    }
//                    return;
//                }
//            }
//            
//            NSLog(@"location:%@", location);
//            
//            if (regeocode)
//            {
//                NSLog(@"reGeocode:%@", regeocode);
//                NSLog(@"reGeocode:%@", regeocode.citycode);
//                model.provinceCode = regeocode.province;
//                model.addInfo = regeocode.formattedAddress;
//                model.lon = location.coordinate.longitude;
//                model.areaCode = regeocode.adcode;
//                model.cityCode = [Helper getCityCodeWithName:regeocode.city];
//                model.cityName = regeocode.city;
//                model.areaName = regeocode.district;
//                model.POIName = regeocode.POIName;
//                model.lat = location.coordinate.latitude;
//                DLog(@"addresssDic==%@",model.addInfo);
//                if (self.GetLocationBlock) {
//                    self.GetLocationBlock(model);
//                }
//            }
//        }];
}
@end
